package com.iad.util;

import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;

import com.iad.core.Core;
import com.iad.entity.Review;
import com.iad.entity.ContactMessage;
import com.iad.entity.WelcomeEmail;

/**
 * This class contains various static mail utility methods.
 * 
 * @author Nick Sophinos
 *
 */

public class Mail {
	static String className = "Mail";

	/**
	 * Mails admin password.
	 * 
	 * @param to the recipient
	 * @param from the sender
	 * @param subject the subject
	 * @param content the content 
	 * @param contentType the content  MIME type
	 * @param userName the user name 
	 * @param password the password 
	 * @exception Exception if error occurs 
	 */
	public static void mailAdminPasswordRetrievalNotification(String to,
			String from, String subject, String contentType, String userName,
			String password) throws Exception {


		StringBuffer mailContentSB = new StringBuffer();

		mailContentSB
				.append("<html>")
				.append("<head>")
				.append("<title>Metabolic Pulse Administrator Password Retrieval</title>")
				.append("<style>")
				.append("</style>\n")
				.append("</head>\n")
				.append("<body>")
				.append("<h3 align='center'>Metabolic Pulse Administrator Password Retrieval</h3>");

		if (password != null) {
			mailContentSB.append("<p>Your login information is below:</p>\n");
			mailContentSB.append("<p>User Name: <strong>" + userName
					+ "<strong></p>\n");
			mailContentSB.append("<p>Password: <strong>" + password
					+ "</strong></p>\n");
		} else {
			mailContentSB.append("<p>No record of user " + userName
					+ " found\n");
		}

		mailContentSB.append("</body>\n").append("</html>\n");

		mailItem(to, from, subject, mailContentSB.toString(), contentType);
	}
	
	
  /**
   * Notifies us of submitted artist review.
   * 
   * @param to the recipient
   * @param from the sender
   * @param subject the subject
   * @param content the content 
   * @param contentType the content  MIME type
   * @param userName the user name 
   * @param password the password 
   * @exception Exception if error occurs 
   */
  public static void mailContactMessage(String to,
      String from, String subject, String contentType, ContactMessage contactMessage) throws Exception {


    StringBuffer mailContentSB = new StringBuffer();

    mailContentSB
        .append("<html>")
        .append("<head>")
        .append("<title>" + subject + "</title>")
        .append("<style>")
        .append("</style>\n")
        .append("</head>\n")
        .append("<body>")
        .append("<h3 align='center'>" + subject + "</h3>");

    mailContentSB.append("<p><strong>Subject: </strong>" + contactMessage.getSubject() + "</p>\n");
    mailContentSB.append("<p><strong>Author: </strong>" + contactMessage.getAuthor() + "</p>\n");
    mailContentSB.append("<p><strong>Message: </strong><br/>" + contactMessage.getContent() + "</p>\n");

    mailContentSB.append("</body>\n").append("</html>\n");

    mailItem(to, from, subject, mailContentSB.toString(), contentType);
  }
  
  
  public static void mailWelcomeEmail(String contentType, WelcomeEmail email) throws Exception {


    StringBuffer mailContentSB = new StringBuffer();

    mailContentSB
        .append("<html>")
        .append("<head>")
        .append("<title>" + email.getSubject() + "</title>")
        .append("<style>")
        .append("</style>\n")
        .append("</head>\n")
        .append("<body>")
        .append("<h3 align='center'>" + email.getSubject() + "</h3>");

    mailContentSB.append(
    "<p>\n" +
    "<b>Welcome " + email.getFirstName() + " " + email.getLastName() + " to Independent Artists Direct.</b>\n" +
    "</p>\n" +
    "<p>\n" +
    "Your band, <b> " + email.getBandName() + "</b>, is now hosted at:  \n" + 
    "<a href='http://www.independentartistsdirect.com/" + email.getLogin() + 
    "'>http://www.independentartistsdirect.com/" + email.getLogin() + "</a>\n" +
    "</p>\n" +
    "<p>\n" +
    "Your login name is <b>" + email.getLogin() + "</b> and the password that you chose is <b>" + email.getPassword() + "</b>\n" +
    "</p>\n" +
    "</p>\n" +
    "One of the first things that you probably want to do is to download the " + 
    "<a href='http://www.independentartistsdirect.com/docs/iad_manual.pdf'>IAD Site Management Manual</a>,<br/>\n" + 
    "a 16 page PDF that explains everything you need to know in order to get the most out of your site." + 
    "</p>\n" +
    "<p>\n" +
    //"Instructions for logging in are shown below: \n" + 
    "<b>Instructions for logging in are to be found " +
    "<a href='http://www.independentartistsdirect.com/docs/iad_manual.pdf'>there</a> as well.\n" + 
    //"<b>Instructions for logging in are to be found there as well. \n" + 
    "</p>" + 
    //"<image src='http://www.independentartistsdirect.com/docs/iad_manual_Page_02.jpg'>" + 
    "\n"); 
   
    mailContentSB.append("</body>\n").append("</html>\n");

    mailItem(email.getRecipient(), email.getAuthor(), email.getSubject(), mailContentSB.toString(), contentType);
  }
	
	 /**
   * Notifies us of submitted artist review.
   * 
   * @param to the recipient
   * @param from the sender
   * @param subject the subject
   * @param content the content 
   * @param contentType the content  MIME type
   * @param userName the user name 
   * @param password the password 
   * @exception Exception if error occurs 
   */
  public static void mailNewReviewNotification(String to,
      String from, String subject, String contentType, Review review) throws Exception {


    StringBuffer mailContentSB = new StringBuffer();

    mailContentSB
        .append("<html>")
        .append("<head>")
        .append("<title>" + subject + "</title>")
        .append("<style>")
        .append("</style>\n")
        .append("</head>\n")
        .append("<body>")
        .append("<h3 align='center'>" + subject + "</h3>");

    mailContentSB.append("<p><strong>Title: </strong>" + review.getTitle() + "</p>\n");
    mailContentSB.append("<p><strong>Author: </strong>" + review.getAuthor() + "</p>\n");
    mailContentSB.append("<p><strong>Review: </strong><br/>" + review.getContent() + "</p>\n");

    mailContentSB.append("</body>\n").append("</html>\n");

    mailItem(to, from, subject, mailContentSB.toString(), contentType);
  }

	/**
	 * Mails user password.
	 * @param to
	 * @param from
	 * @param subject
	 * @param contentType
	 * @param userName
	 * @param password
	 * @throws Exception
	 */
	public static void mailUserPasswordRetrievalNotification(String to,
			String from, String subject, String contentType, String userName,
			String password) throws Exception {

		StringBuffer mailContentSB = new StringBuffer();

		mailContentSB.append("<html>").append("<head>").append(
				"<title>Metabolic Pulse Password Retrieval</title>").append(
				"<style>").append("</style>\n").append("</head>\n").append(
				"<body>").append(
				"<h3 align='center'>Metabolic Pulse Password Retrieval</h3>");

		if (password != null) {
			mailContentSB.append("<p>Your login information is below:</p>\n");
			mailContentSB.append("<p>User Name: <strong>" + userName
					+ "<strong></p>\n");
			mailContentSB.append("<p>Password: <strong>" + password
					+ "</strong></p>\n");
		} else {
			mailContentSB.append("<p>No record of user " + userName
					+ " found.</p>\n");
		}

		mailContentSB.append("</body>\n").append("</html>\n");
		//AuthenticatedMail.mailItem(to, from, subject, mailContentSB.toString());
		mailItem(to, from, subject, mailContentSB.toString(), "text/html");
	}

	/**
	 * mailItem
	 * send an email message
	 * 
	 * @param to the recipient
	 * @param from the sender
	 * @param subject the subject
	 * @param content the content 
	 * @param contentType the content  MIME type
	 * @exception Exception if error occurs 
	 */
	public static void mailItem(String to, String from, String subject,
			String content, String contentType) throws Exception {
		
		try {

			String mailServer = Core.getMailServer();

			Properties props = new Properties();
			props.put("mail.host", mailServer);

			Session mailSession = Session.getInstance(props, null);

			// Prepare our mail message
			Message message = new MimeMessage(mailSession);
			message.setFrom(new InternetAddress(from));
			InternetAddress dests[] = new InternetAddress[] { new InternetAddress(
					to) };
			message.setRecipients(Message.RecipientType.TO, dests);
			message.setSubject(subject);
			message.setContent(content, contentType);

			// Send our mail message
			Transport.send(message);
			Core.getServletContext().log("Item mailed to " + to);
		} catch (Throwable t) {
			Core.getServletContext().log("EXCEPTION: " + t.toString());
			//throw new Exception("Mail::mailItem() "+t.toString());
		}
	}

	/**
	 * mailItem
	 * send an email message to a list of recipients
	 * 
	 * @param to the recipient
	 * @param from the sender
	 * @param subject the subject
	 * @param content the content 
	 * @param contentType the content  MIME type
	 * @exception Exception if error occurs 
	 */
	public static void mailItem(List to, String from, String subject,
			String content, String contentType) throws Exception {
		
		String logId = Util.getLogId(className, "mailItem");
		Log log = Core.getLogger();
		log.debug(logId);
		
		try {

			String mailServer = Core.getMailServer();

			Properties props = new Properties();
			props.put("mail.host", mailServer);

			Session mailSession = Session.getInstance(props, null);

			// Prepare our mail message
			Message message = new MimeMessage(mailSession);
			message.setFrom(new InternetAddress(from));
			InternetAddress dests[] = new InternetAddress[to.size()];

			Iterator it = to.iterator();
			int i = 0;
			while (it.hasNext()) {
				dests[i] = new InternetAddress((String) it.next());
				i++;
			}

			message.setRecipients(Message.RecipientType.TO, dests);
			message.setSubject(subject);
			message.setContent(content, contentType);

			// Send our mail message
			Transport.send(message);
			Core.getServletContext().log(logId + "Item mailed to " + to);
		} catch (Throwable t) {
			Core.getServletContext().log(logId + "EXCEPTION: " + t.toString());
			//throw new Exception("Mail::mailItem() "+t.toString());
		}
	}

}
